package com.epalmpay.job;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.enumdef.CommonEnum.RunStatus;
import com.epalmpay.enumdef.CommonEnum.TaskType;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.operator.ISysLogService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class ProfitOutMontyMonthTaskJob {
     
	@Resource
	private ISysLogService sysLogService;
	@Resource
	private IProfitStatisService profitStatisService;
	
	protected Logger logger = Logger.getLogger(this.getClass());	
	
	/**
	 * 分润月出款任务(在分润月统计之后执行)
	 * 每月5号凌晨2点30分执行一次
	 */
	@Scheduled(cron="0 30 2 5 * ?")
	public void  run(){

		//统计日期
		String statisDate = null;
		Date taskDate = null;
		String taskName = null;
		StringBuffer sb = new StringBuffer(); 
		try {
			//取得上月日期字符串yyyymm
			statisDate = DateUtil.getLastMonth(1);
			//月份统一转成YYYYMM01格式的日期
			taskDate = DateUtil.fomatDate(statisDate + "01",DateUtil.sdfDays);
			taskName = TaskType.ProfitOutMoneyMonthTask.getName();

			profitStatisService.profitOutMontyMonth(taskDate);
			logger.info(sb.append("计划任务:")
					.append(taskName)
					.append("统计日期：").append(statisDate).append("执行成功！"));
		
		} catch (ApplicationException ae) {
			logger.info(sb.append("计划任务:")
					.append(taskName)
					.append("统计日期：").append(statisDate).append("执行结果：").append(ae.errMsg));				
		}
		 catch (Exception e) { 
			 try{
				sysLogService.recordSysTaskLog(TaskType.ProfitOutMoneyMonthTask.getType(),
						taskDate, RunStatus.Fail.getType());
			 }catch(Exception sube){
					logger.info(sb.append("计划任务:")
							.append(taskName)
							.append("统计日期：").append(statisDate).append("执行失败！"));				 
				 logger.error(sube);
			 }
			e.printStackTrace();
			logger.info(sb.append("计划任务:")
					.append(taskName)
					.append("统计日期：").append(statisDate).append("执行失败！"));			
			logger.error(e);
		}
	}

}
